/**
 * @format
 * @Author: TC
 * @Date: 2025-06-10 10:00:53
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-10 11:11:08
 */

import { instantiate, Node, Prefab } from "cc";
import { app } from "../App";
import { EntityComponent } from "../Module/Ecs/EntityComponent";
import { EntityUnit } from "../Module/Ecs/EntityUnit";

/**
 * 实体管理
 */
export class EntityManager {
    private _entityUid: number = -1;
    private _entityMap: Map<number, EntityUnit> = null;

    constructor() {
        this._entityMap = new Map();
        this._entityUid = 0;
    }

    public add(bundle: string, path: string, cb?: (node: Node) => void): void {
        app.resMgr.loadPrefab(bundle, path, (p: Prefab) => {
            const node = instantiate(p);
            // this.nodeBattle.addChild(char);
            // app.sceneMgr.getCurrCanvasNode().getChildByName("PHYSICS_2D_DEBUG_DRAW").layer = Layers.Enum.DEFAULT;\
            const comp = node.getComponent(EntityComponent);
            if (!comp) {
                app.log.error(bundle + "/" + path + " is has not entityComponent");
                return;
            }
            let unit: EntityUnit = new EntityUnit(comp);
            unit.uid = comp.uid = this._entityUid;
            this._entityMap.set(this._entityUid, unit);
            this._entityUid++;
            if (cb) cb(node);
        });
    }

    /**
     * 根据唯一id删除一个个体
     * @param uid 唯一id
     */
    public remove(uid: number): void {
        let unit = this._entityMap.get(uid);
        if (unit) {
            unit.release();
            this._entityMap.delete(uid);
            unit = null;
        }
    }

    public getEntity(uid: number): EntityUnit {
        return this._entityMap.get(uid);
    }

    /**
     * 释放
     */
    public release(): void {
        for (let i = 0; i < this._entityUid; i++) {
            this.remove(i);
        }
        this._entityMap.clear();
    }
}
